<?php

namespace App\Model;

use App\BaseModel;

class UserWechat extends BaseModel
{
    protected $table = "user_wechats";

    public function user()
    {
        return $this->belongsTo('App\User','user_id','id');
    }
    //保存微信用户信息
    public static function saveWeChatUser($weChatUserInfo)
    {
        $user = $weChatUserInfo;

        if(!$user) return false;

        $openid = false;
        $userInfo = false;

        if(isset($user['original']) && !empty($user['original']) && isset($user['original']['openid']) && $user['original']['openid'] ) {
            $userInfo = $user['original'];
            $openid = $user['original']['openid'];
        }

        if(!$openid && isset($user['token']) &&  isset($user['token']['openid']) && $user['token']['openid']){
            $openid = $user['token']['openid'];
        }

        if($openid) {
            $m = self::where('openid','=',$openid)->first();

            if(!$m) {
                $m = new UserWechat();
                $m->openid = $openid;
            }

            if($userInfo){
                $m->nickname = $userInfo['nickname'];
                $m->avatar_url = $userInfo['headimgurl'];
                $m->province = $userInfo['province'];
                $m->city = $userInfo['city'];
                $m->country = $userInfo['country'];
                $m->gender = $userInfo['sex'];
            }

            if($m->save()) {
                return $m;
            }
        }

        return false;
    }
}
